<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row>
        <el-col :span="8" class="Search">
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            />
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe row-key="id">
        <el-table-column type="index" />
        <el-table-column label="用户名" prop="name" />
        <el-table-column label="入职时间" prop="entryTime" />
        <el-table-column label="电话" prop="phone" />
        <el-table-column label="职位" prop="job_Name"> </el-table-column>
        <el-table-column label="用户状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.peopleState"
              @change="userStateChanged(scope.row)"
              :disabled="scope.row.id == 1"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <div v-if="scope.row.id == 1" style="text-align: center">
              <el-tag type="info"
                ><i class="el-icon-lock"></i> 该用户已锁定</el-tag
              >
            </div>
            <div v-else>
              <!-- 修改按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row)"
              />
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(scope.row.phone)"
              />
              <!-- 分配角色按钮 -->
              <el-tooltip
                effect="dark"
                content="内容分配"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="setRole(scope.row)"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" />
        </el-form-item>

        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="addForm.people_id" placeholder="请选择角色">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" />
        </el-form-item>

        <el-form-item label="手机" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="职位">
          <el-select v-model="editForm.people_id" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="内容分配"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="closeClassify"
    >
      <div>
        <p>当前的用户：{{ userInfo.name }}</p>
      </div>
      <div>
        <p>
          当前项目：
          <el-select
            v-model="xiangmu"
            placeholder="请选择"
            @change="getProjects"
          >
            <el-option
              v-for="item in xiangmuoptions"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </p>
        <p class="fen">
          当前项目下的权限：
          <el-tree
            ref="role"
            :data="rights"
            show-checkbox
            node-key="id"
            :default-expand-all="true"
            :default-checked-keys="defaultkey"
            :props="defaultProps"
            @check-change="getCheckedNodes"
          />
        </p>
        <!-- <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="setapprole">确 定</el-button>
        </span> -->
      </div>
      <template slot="footer" class="dialog-footer">
        <el-button @click="closeRoleDialog">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getproject, getproclassify, getclassify } from "../../api/project";
import {
  userlist,
  adduser,
  updateuser,
  delectuser,
  updateuserRole,
  updataapp,
} from "../../api/user";

export default {
  data() {
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };

    return {
      id: "",
      options: [],
      xiangmuoptions: [],
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10,
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        name: "",
        password: "",
        phone: "",
        peopleState: "1",
        people_id: "",
      },
      // 添加表单的验证规则对象
      addFormRules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "用户名的长度在1~10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "用户名的长度在1~15个字符之间",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        phone: [
          { required: true, message: "请输入用户手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色Id值
      selectedRoleId: "",
      // 已选中的项目id值
      xiangmu: "",
      // 修改用户的手机号(唯一的，修改手机号之前的手机号)
      pho: "",
      setdata: {
        phone: "",
        role_id: "",
      },
      // 项目权限
      rights: [],
      // a: true,
      rolerights: false,

      role: {},
      defaultkeys: [],
      defaultProps: {
        label: "name",
        children: "children",
      },
      ids: {
        id: "",
        pro_id: "",
        moduls: [],
      },
      addclassify: [],
    };
  },
  created() {
    this.getUserList();
    this.datalist();
  },
  watch: {
    id: {
      immediate: true, //初始化时让handler调用一下
      //handler什么时候调用？当isHot发生改变时。（一个参数就是newValue）
      async handler(newValue, oldValue) {
        // console.log('isHot被修改了', newValue, oldValue)
        // this.ids.pro_id = newValue
        // let res = await getapp({ pro_id: newValue })
        // if (res.code == 200) {
        //   this.rights = res.role
        //   console.log(res, "quanxainm");
        // }
      },
    },
  },
  computed: {
    defaultkey() {
      return this.$store.state.classify;
    },
    upKeys() {
      return this.$store.state.classify;
    },
  },
  methods: {
    getCheckedNodes(eee, aa) {
      console.log(eee, aa);
      if (aa) {
        this.$store.commit("addKeys", eee);
      } else {
        this.$store.commit("delKeys", eee);
      }

      // console.log(arr);
      // this.addclassify = [...this.defaultkeys, ...arr];
      // console.log(this.addclassify);
    },
    closeRoleDialog() {
      this.setRoleDialogVisible = false;
      this.$refs["role"].setCheckedKeys([]);
    },
    async getProjects(e) {
      console.log(e);
      this.id = e;
      let dic = {
        pro_id: e,
      };
      let da = {
        id: this.userInfo.id,
        pro_id: e,
      };
      const data = await getproclassify(dic);
      // console.log(data);
      if (data.code === 200) {
        this.rights = data.data;
        const cdata = await getclassify(da);
        console.log(cdata, "cccccccccc  ");
        const arr = [];
        if (cdata.code === 200) {
          cdata.data.modules.forEach((item) => {
            arr.push(item.id);
          });
          this.defaultkeys = arr;
          this.$store.commit("defaultKeys", arr);
        }
      }
    },
    async datalist() {
      const data = await getproject();
      if (data.code === 200) {
        data.data.forEach((item) => {
          this.xiangmuoptions.push({
            value: item.id,
            label: item.name,
          });
        });
      }
    },
    async getUserList() {
      const res = await userlist(this.queryInfo);
      if (res.code === 200) {
        this.options = [];
        console.log(res);
        this.total = res.total;
        res.role.forEach((item) => {
          this.options.push({
            value: item.id,
            label: item.jobName,
          });
        });
        let users = res.data;
        let roles = res.role;
        let newlist = [];
        users.map((item) => {
          roles.map((opt) => {
            if (opt.id == item.people_id) {
              item.job_Name = opt.jobName;
              newlist.push(item);
            }
          });
        });
        const T = setTimeout(() => {
          this.userlist = newlist;
          console.log(newlist);
          clearTimeout(T);
        }, 100);
      }
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },

    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        if (!this.addForm.people_id) {
          this.$message.error("请选择角色");
          return;
        }
        const res = await adduser(this.addForm);
        if (res.code === 200) {
          this.$message.success("添加用户成功！");
          this.addDialogVisible = false;
          this.getUserList();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 展示编辑用户的对话框
    async showEditDialog(d) {
      console.log(d);
      this.editForm = d;
      this.pho = d.phone;
      this.editDialogVisible = true;
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起修改用户信息的数据请求
        this.editForm.pho = this.pho;
        const result = await updateuser(this.editForm);
        if (result.code == 200) {
          // 关闭对话框
          this.editDialogVisible = false;
          // 刷新数据列表
          this.getUserList();
          // 提示修改成功
          this.$message.success("更新职位信息成功！");
        }
      });
    },
    // 根据Id删除对应的用户信息
    async removeUserById(phone) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      const res = await delectuser(phone);

      if (res.code == 200) {
        this.$message.success("删除用户成功！");
        this.getUserList();
      }
    },

    // 展示分配角色的对话框
    async setRole(userInfo) {
      console.log(userInfo, "userinfo");
      this.ids.id = userInfo.id;
      this.userInfo = userInfo;
      this.setRoleDialogVisible = true;
    },

    // 监听 switch 开关状态的改变
    async userStateChanged(userinfo) {
      this.pho = userinfo.phone;
      userinfo.pho = this.pho;
      const res = await updateuser(userinfo);

      if (res.code == 200) {
        this.$message.success("用户状态修改成功");
        this.getUserList();
      }
    },

    async saveRoleInfo() {
      // console.log(data);
      let da = {
        id: this.userInfo.id,
        pro_id: this.id,
        modules: this.$store.state.classify,
      };

      const res = await updateuserRole(da);
      console.log(res);
      if (res.code == 200) {
        const arr = [];
        this.getUserList();
        this.$store.commit("newArr", arr);
        this.setRoleDialogVisible = false;
        this.$message.success(res.msg);
        this.closeClassify();
      }
      // history.go(0);
    },
    // 关闭分配角色的Dialog
    closeClassify() {
      this.xiangmu = "";
      this.rights = [];
      this.closeRoleDialog();
    },
    async setapprole() {
      var arr1 = this.$refs["role"].getCheckedKeys();
      var arr2 = this.$refs["role"].getHalfCheckedKeys();
      this.ids.moduls = arr1;
      console.log(this.ids.moduls, "选中的权限");
      var res = await updataapp(this.ids);
      if (res.code == 200) {
        this.$message.success("更新成功");
        this.getUserList();
      } else {
        this.$message.error("更新失败");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-row {
  margin: 0;
  .Search {
    margin-right: 12px;
  }
}
.el-table {
  margin: 20px 0;
}
.el-pagination {
  float: right;
  margin-bottom: 20px;
}
</style>
